#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/07/15
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from datetime import datetime
from project.flasky import db
from project.define import db_logger


DataName = "在场记录"
TableName = "app_records_parking"


class RecordParking(db.Model):
    """
    在场记录
    """
    __tablename__ = TableName
    # 在场ID
    ParkingID = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
    # 入场ID
    EntranceID = db.Column(db.Integer, nullable=False)
    # 入场闸机
    EntranceGateName = db.Column(db.String(16))
    # 入场时间
    EntranceTime = db.Column(db.DateTime, nullable=False)
    # 车型地感
    VehicleType = db.Column(db.String(16), nullable=False)
    # 车牌结果
    LicensePlate = db.Column(db.String(16), nullable=False)
    # 结果图片路径
    LicensePlateImg = db.Column(db.String(128))
    # 时租票号
    TicketNumber = db.Column(db.String(128))
    # 月租卡号
    CardNumber = db.Column(db.String(64))
    # 入场温度
    EntranceTemp = db.Column(db.Float)
    # 在场类型
    ParkingType = db.Column(db.String(16), nullable=False)
    # 车位名称
    PlaceName = db.Column(db.String(16))
    # 月租用户
    UserID = db.Column(db.Integer)
    # 缴费ID
    ChargeID = db.Column(db.Integer)
    # 收费处
    CashierName = db.Column(db.String(64))
    # 缴费时间
    ChargeTime = db.Column(db.DateTime)
    # 离场ID
    ExitID = db.Column(db.Integer)
    # 离场闸机
    ExitGateName = db.Column(db.String(16))
    # 离场时间
    ExitTime = db.Column(db.DateTime)
    # 离场温度
    ExitTemp = db.Column(db.Float)
    # 删除状态
    Deleted = db.Column(db.Boolean, default=False)

    def __init__(self, **kwargs) -> None:
        super().__init__()
        self.EntranceID = kwargs.get('EntranceID')
        self.EntranceGateName = kwargs.get('GateName')
        self.VehicleType = kwargs.get('VehicleType')
        self.LicensePlate = kwargs.get('LicensePlate')
        self.LicensePlateImg = kwargs.get('LicensePlateImg')
        self.TicketNumber = kwargs.get('TicketNumber')
        self.CardNumber = kwargs.get('CardNumber')
        self.ParkingType = kwargs.get('ParkingType')
        self.EntranceTemp = kwargs.get('GateTemp')
        self.PlaceName = kwargs.get('PlaceName')
        self.UserID = kwargs.get('UserID')
        entrance_time = kwargs.get('GateTime')
        if entrance_time:
            self.EntranceTime = datetime.strptime(entrance_time, '%Y/%m/%d %H:%M:%S')

    def datetime_string(self, val):
        """
        datetime转字符串
        """
        if isinstance(val, datetime):
            return val.strftime('%Y/%m/%d %H:%M:%S') 

    def to_dict(self):
        """
        转换键值对
        """
        def convert_data(name):
            val = getattr(self, name)
            if isinstance(val, datetime):
                return val.strftime('%Y/%m/%d %H:%M:%S')
            return val

        return dict([(c.name, convert_data(c.name)) for c in self.__table__.columns])

    def modify_ticket_parking(self, **kwargs):
        """
        补票更新
        """
        try:
            self.EntranceTime = datetime.strptime(kwargs.get('EntranceTime'), '%Y/%m/%d %H:%M:%S')
            self.VehicleType = kwargs.get('VehicleType')
            self.EntranceGateName = kwargs.get('CashierName')
            db.session.commit()
            db_logger.debug(f"{TableName} => 更新在场信息：{kwargs}")
            return self.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 更新在场信息错误! 数据：{kwargs} 原因：{e}")

    def refresh_charge_info(self, **kwargs):
        """
        刷新收费信息
        """
        try:
            self.ChargeID = kwargs.get('ChargeID')
            self.CashierName = kwargs.get('CashierName')
            self.ChargeTime = datetime.strptime(kwargs.get('ChargeTime'), '%Y/%m/%d %H:%M:%S')
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 更新收费信息：{kwargs}错误! 原因：{e}")

    @staticmethod
    def columns_name():
        """
        标题
        """
        return {
            "ParkingID":"在場ID","EntranceTime":"入場時間","EntranceGateName":"入口名稱","VehicleType":"車型","LicensePlate":"車牌結果",
            "LicensePlateImg":"識別圖片","TicketNumber":"時租票號","CardNumber":"月租卡號","EntranceTemp":"入場體溫",
            "ParkingType":'泊車類型',"PlaceName":"車位名稱","ChargeTime":"繳費時間","ExitTime":"離場時間","ExitGateName":"出口名稱","ExitTemp":"離場體溫"
        }

    @staticmethod
    def selected_data(**kwargs):
        """
        选中数据
        """
        parking_id = kwargs.get('ParkingID')
        if parking_id:
            return RecordParking.query.filter_by(ParkingID=parking_id).first()

    @staticmethod
    def generate_filters(**kwargs):
        """
        筛选器
        """
        filters = set()
        if "Deleted" not in kwargs:
            filters.add(RecordParking.Deleted == False)
        for k, v in kwargs.items():
            if v:
                if hasattr(RecordParking, k):
                    if k == 'VehicleType':
                        filters.add(RecordParking.VehicleType == v)
                    elif k == 'LicensePlate':
                        filters.add(RecordParking.LicensePlate.like(f"%{v}%"))
                    elif k == 'TicketNumber':
                        filters.add(RecordParking.TicketNumber.like(f"%{v}%"))
                    elif k == 'CardNumber':
                        filters.add(RecordParking.CardNumber.like(f"%{v}%"))
                    elif k == 'ParkingType':
                        filters.add(RecordParking.ParkingType == v)
                    elif k == 'EntranceTime':
                        if " - " in v:
                            start, end = [datetime.strptime(i, "%Y/%m/%d %H:%M:%S") for i in v.split(' - ') ]
                            filters.add(RecordParking.EntranceTime.between(start, end))
                    elif k == 'ExitTime':
                        if " - " in v:
                            start, end = [datetime.strptime(i, "%Y/%m/%d %H:%M:%S") for i in v.split(' - ') ]
                            filters.add(RecordParking.ExitTime.between(start, end))
        return filters

    @staticmethod
    def delete_data(**kwargs):
        """
        删除
        """
        try:
            r = RecordParking.selected_data(**kwargs)
            if r:
                r.Deleted = True
                db.session.commit()
                db_logger.debug(f"{TableName} => 删除{DataName}成功：{kwargs}")
                return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 删除{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def lane_entrance_record(**kwargs):
        """
        入场纪录
        """
        try:
            r = RecordParking(**kwargs)
            db.session.add(r)
            db.session.commit()
            ret = r.to_dict()
            db_logger.debug(f"{TableName} => 新增{DataName} 入场成功：{ret}")
            return ret
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 新增{DataName} 入场失败：{kwargs} 原因：{e}")

    @staticmethod
    def lane_exit_record(**kwargs):
        """
        离场记录
        """
        try:
            r = RecordParking.selected_data(**kwargs)
            if r:
                r.ExitID = kwargs.get('ExitID')
                r.ExitGateName = kwargs.get('GateName')
                r.ExitTime = datetime.strptime(kwargs.get('GateTime'), '%Y/%m/%d %H:%M:%S')
                r.ExitTemp =kwargs.get('GateTemp')
                db.session.commit()
                db_logger.debug(f"{TableName} => 更新{DataName} 离场成功：{kwargs}")
                return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 更新{DataName} 离场失败：{kwargs} 原因：{e}")

    @staticmethod
    def modify_data(**kwargs):
        """
        修改
        """
        try:
            update = False
            r = RecordParking.selected_data(**kwargs)
            if r:
                for k, v in kwargs.items():
                    if hasattr(r, k):
                        if getattr(r, k) != v:
                            setattr(r, k, v)
                            update = True
                if update:
                    try:
                        db.session.commit()
                        db_logger.debug(f"{TableName} => 更新{DataName}成功：{kwargs}")
                        return r.to_dict()
                    except Exception as e:
                        db.session.rollback()
                        db_logger.error(f"{TableName} => 更新{DataName}失败：{kwargs} 原因：{e}")
        except Exception as e:
            db_logger.error(f"{TableName} => 更新{DataName}参数错误：{kwargs} 原因：{e}")
